package com.gewu.teday.utils;

import static android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;

import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;


public class Util {


    public static void setNaviBarColor(Window window) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                window.getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                );
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setNavigationBarColor(Color.TRANSPARENT);
            }
        }
    }

    public static void setStatusOrNavigationColor(Activity activity, int color) {
        Window window = activity.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(ContextCompat.getColor(activity, color));
            window.setNavigationBarColor(Color.TRANSPARENT);
        }

        ViewGroup mContentView = activity.findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            mChildView.setFitsSystemWindows(true);
        }

        if (ColorUtils.calculateLuminance(color) >= 0.5) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
            } else {
                window.getDecorView().setSystemUiVisibility(0);
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.getDecorView().setSystemUiVisibility(SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            } else {
                window.getDecorView().setSystemUiVisibility(0);
            }
        }
    }

    public static void setStatusBarColor(Activity activity, int color) {
        Window window = activity.getWindow();
        int topColor = activity.getResources().getColor(color);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(topColor);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (ColorUtils.calculateLuminance(color) >= 0.5) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    window.getDecorView().setSystemUiVisibility(SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                }
            } else {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            }
        } else {
            Toast.makeText(activity, "版本过于低", Toast.LENGTH_SHORT).show();
        }
    }

    public static int getStatusBarHeight(Context context) {
        int result = 24;
        int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resId > 0) {
            result = context.getResources().getDimensionPixelSize(resId);
        } else {
            result = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                    result, Resources.getSystem().getDisplayMetrics());
        }
        return result;
    }

    /**
     * 代码设置沉浸式状态栏
     *
     * @param activity 当前activity
     */
    public static void setStatusBarTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
            Window window = activity.getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
                window.setStatusBarColor(Color.TRANSPARENT);
//                setNavigationBarColor(window);
            } else {
                attributes.flags |= flagTranslucentStatus | flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }


    //获取选择的图片地址
    public static String getRealPathFromUri(Context context, Uri uri) {
        Log.d("tgw", "getRealPathFromUri:uri.getScheme() " + uri.getScheme());
        if (Build.VERSION.SDK_INT >= 19) { // api >= 19  如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
            String filePath = null;
            //判断该Uri是否是document封装过的DocumentsContract.isDocumentUri(mAct, uri)
            if (DocumentsContract.isDocumentUri(context, uri)) {
                // 如果是document类型的 uri, 则通过document id来进行处理
                String documentId = DocumentsContract.getDocumentId(uri);
                if ("com.android.providers.media.documents".equals(uri.getAuthority())) { // MediaProvider
                    // 使用':'分割用split('.')方法将字符串以"."开割形成一个字符串数组，
                    // 然后再通过索引[1]取出所得数组中的第二个元素的值。
                    String id = documentId.split(":")[1];
                    Log.d("tgw1", "getRealPathFromUri: " + documentId + "--" + id);
                    String selection = MediaStore.Images.Media._ID + "=?";
                    String[] selectionArgs = {id};
                    //如果要查询图片，地址：MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                    filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
                    Log.d("tgwdocuments", "getRealPathFromUri: " + filePath + "==" + selectionArgs);
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { // DownloadsProvider
                    //这个方法负责把id和contentUri连接成一个新的Uri=: content://downloads/public_downloads/documentId
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                    filePath = getDataColumn(context, contentUri, null, null);
                    Log.d("tgwcontentUri", "getRealPathFromUri: " + filePath);
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {

                // 如果是 content 类型的 Uri
                // 返回文件头 uri.getScheme() 如：content  file 等等
                filePath = getDataColumn(context, uri, null, null);
                Log.d("tgwcontent", "getRealPathFromUri: " + filePath);

            } else if ("file".equals(uri.getScheme())) {

                // 如果是 file 类型的 Uri,直接获取图片对应的路径
                filePath = uri.getPath();
                Log.d("tgwfile", "getRealPathFromUri: " + filePath);
            }
            return filePath;

        } else { // api < 19
            return getDataColumn(context, uri, null, null);
        }
    }


    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        String path = null;

        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            //uri提供内容的地址，projection查询要返回的列，
            // selection  ：查询where字句， selectionArgs ： 查询条件属性值 ，sortOrder ：结果排序规则
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                //getColumnIndexOrThrow 从零开始返回指定列名称，如果不存在将抛出IllegalArgumentException 异常。
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
                Log.d("tgwgetDataColumn", "getDataColumn: " + path);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return "file://" + path;
    }

    private static Bitmap bitmap = null;

    public static Bitmap getBitmap(Context context, String uri) {
        try {
            ContentResolver contentResolver = context.getContentResolver();
            bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(Uri.parse(uri)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static String getImagePath(Context context, Uri uri, Intent data) {
        Uri selectedImage = data.getData();
        if (selectedImage != null) {
            String uriStr = selectedImage.toString();
            String path = uriStr.substring(10, uriStr.length());
            if (path.startsWith("com.sec.android.gallery3d")) {
                Log.e("Method selectImage", "It's auto backup pic path:" + selectedImage.toString());
                return null;
            }
        }
        final String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        String mImgPath;
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mImgPath = cursor.getString(columnIndex);
            cursor.close();
        } else {
            mImgPath = selectedImage != null ? selectedImage.getPath() : null;
        }
        return mImgPath;
    }

    static List<String> mothlist = new ArrayList<>();

    /**
     * 获取30天数据
     */
    public static void getdatelist() {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        for (int i = 1; i <= 31; i++) {
            calendar.add(Calendar.DATE, -1);
            Date d = calendar.getTime();
            String day = sdf.format(d);
            formartTime(day);
            mothlist.add(day);
        }
    }

    /**
     * 截取规定时间字符串   2022-08-10   -->  08-10
     *
     * @param time
     * @return
     */
    public static String formartTime(String time) {
        int i = time.indexOf("-");
        String substring = time.substring(i + 1, time.length());
        return substring;
    }

    public static List<String> getMothlist() {
        if (mothlist != null && mothlist.size() != 0) {
            mothlist.clear();
        }
        getdatelist();
        return mothlist;
    }

    /**
     * 小数拆分算法
     *
     * @param number
     * @param numberOfSplits
     * @return
     */
    public static List<Float> splitInto(float number, int numberOfSplits, float max, float min) {
        List<Float> nums = new ArrayList<>();
        float rawData = number;
        float temp = 0;
        float j;
        for (int i = 0; i <= numberOfSplits - 1; i++) {
            if (number > 1) {
                j = makeRandom(max, min, 2).floatValue();
                number -= j;  //270
                temp += j;  //30
                nums.add(j); //30
            } else if (temp + 1 == rawData) {
                if (number > 0) {
                    nums.add(number);
                    for (int l = 1; l < numberOfSplits - i; l++) {
                        nums.add((float) 0);
                    }
                } else {
                    j = makeRandom(max, min, 2).floatValue();
                }
            } else {
                nums.add((float) 0);
            }
        }
        return nums;
    }


    public static int[] splitInto(int number, int[] numberOfSplits) {
        Random random = new Random();
        for (int i = 1; i < numberOfSplits.length; i++) {
            if (number > 1) {
                int j = random.nextInt(number - 1) + 1;
                number -= j;
                numberOfSplits[i] = j;
            } else if (number == 1) {
                numberOfSplits[i + 1] = number;
                break;
            }
        }
        return numberOfSplits;
    }

    /**
     * 随机生成小数
     *
     * @param max
     * @param min
     * @param scale
     * @return
     */
    public static BigDecimal makeRandom(float max, float min, int scale) {
        BigDecimal cha = new BigDecimal(Math.random() * (max - min) + min);
        return cha.setScale(scale, BigDecimal.ROUND_HALF_DOWN);//保留 scale 位小数，并四舍五入
    }

    /**
     * 获取今日时间
     *
     * @return
     */
    public static String getTime() {
        Date dNow = new Date();   //当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        dBefore = calendar.getTime();   //得到前一天的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
        return sdf.format(dBefore);
    }

    /**
     * 获取规定时间距离今天的所有时间日期
     *
     * @param startDate
     * @return
     */
    public static List<String> splitDateList(String startDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<String> listDate = new ArrayList<>();
        try {
            Calendar calendar = Calendar.getInstance();
            Date parseStart = dateFormat.parse(startDate);

            Date parseEnd = dateFormat.parse(getTime());
            if (parseStart != null) {
                calendar.setTime(parseStart);
            }
            calendar.add(Calendar.DATE, 1);
            while (calendar.getTime().before(parseEnd)) {
                String format = dateFormat.format(calendar.getTime());
                listDate.add(format);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listDate;
    }


    /**
     * 判断时间是否在规定时间之前
     * @return
     */
    public static boolean afterTimeCalendar() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //设置时间格式
            //设置当前时间
            Calendar date = Calendar.getInstance();
        try {
            date.setTime(sdf.parse(getTimeH()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //设置开始时间
            Calendar begin = Calendar.getInstance();
        try {
            begin.setTime(sdf.parse(getTime()+" 14:00:00"));//开始时间
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //处于开始时间之后，和结束时间之前的判断
        return date.after(begin);
    }



    public static boolean afterAndbeforeTimeCalendar() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //设置时间格式
        //设置当前时间
        Calendar date = Calendar.getInstance();
        try {
            date.setTime(sdf.parse(getTimeH()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //设置开始时间
        Calendar begin = Calendar.getInstance();
        try {
            begin.setTime(sdf.parse(getTime()+" 9:00:00"));//开始时间
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar beginEnd = Calendar.getInstance();
        try {
            beginEnd.setTime(sdf.parse(getTime()+" 23:00:00"));//开始时间
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Date today = new Date();
        Calendar c=Calendar.getInstance();
        c.setTime(today);
        int weekday=c.get(Calendar.DAY_OF_WEEK);
        
        //在9。00之后23.00之前 并且是周四
        return date.after(begin)&&date.before(beginEnd)&&weekday==5;
    }

    public static String getTimeH() {
        Date dNow = new Date();   //当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        dBefore = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间格式
        return sdf.format(dBefore);
    }



    public static boolean isValidDate(String str) {
        boolean convertSuccess=true;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            convertSuccess=false;
        }
        return convertSuccess;
    }


    public static String formatTime(long str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        date.setTime(str);
        return format.format(date);
    }


    public static String StringToDate(String time) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date;
        date = format.parse(time);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = null;
        if (date != null) {
            s = format1.format(date);
        }
        return s;
    }
}

